package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.service.IAdminService;
import com.example.crossborderecommerce.service.ICustomerService;
import com.example.crossborderecommerce.service.IRoleService;
import com.example.crossborderecommerce.utils.DecodeToken;
import com.example.crossborderecommerce.utils.TokenUtil;
import org.apache.commons.collections4.map.AbstractMapDecorator;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 管理员模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private IAdminService adminService;
    @Resource
    private TokenUtil TokenUtil;
    @Resource
    private IRoleService roleService;

    /**
     * 登录
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", admin.getUsername());
        queryWrapper.eq("password", admin.getPassword());
        Admin res = adminService.getOne(queryWrapper);

        if(res != null) {
            String token = TokenUtil.genToken(res.getId().toString(),res.getRole());
            // 生成响应对象
            Map<String,String> map = new HashMap<>();
            map.put("token",token);
            map.put("role",res.getRole());
            map.put("name",res.getName());
            res.setLastLoginTime(LocalDateTime.now());
            update(res);
            return Result.success("登陆成功!",map);
        }
        return Result.error("账户密码错误！");
    }

    /**
     * 注册
     * @param admin
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody Admin admin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", admin.getUsername());
        Admin admin1 = adminService.getOne(queryWrapper);
        if(admin1 == null) {
            String role1 = roleService.findNameByAuthority(admin.getRole());
            admin.setRoleName(role1);
            boolean res = adminService.save(admin);
            if(res) {
                return Result.success("用户注册成功！");
            }
            return Result.success("登陆成功!");
        }
        else {
            return Result.error("当前用户名已被注册存在！");
        }
    }

    /**
     * 获取管理员总数
     * @return
     */
    @GetMapping("/count")
    public Result count() {
        long count = adminService.count();
        return Result.success("获取管理员数量成功", count);
    }

    /**
     * 获取管理员账户信息
     * @param request
     * @return
     */
    @GetMapping("account")
    public Result getAdminAccount(HttpServletRequest request) {
        DecodeToken decodeToken = new DecodeToken(request);
        String adminId = decodeToken.getAdminId();
        String role = decodeToken.getRole();

        Map<String, String> map = new HashMap<>();
        map.put("id", adminId);
        map.put("role", role);
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", adminId);
        queryWrapper.eq("role", role);
        Admin admin = adminService.getOne(queryWrapper);
        map.put("name", admin.getName());
        map.put("username", admin.getUsername());
        return Result.success("", map);
    }

    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Admin admin) {
        if(admin.getPassword().isEmpty()) {
            admin.setPassword(admin.getPhone());//默认手机号为密码
        }
        String role1 = roleService.findNameByAuthority(admin.getRole());
        admin.setRoleName(role1);
        boolean res = adminService.save(admin);
        if(res) {
            return Result.success("添加管理员成功！");
        }
        return Result.error("添加管理员失败！");
    }

    /**
     * 根据管理员id获取管理员信息
     * @param id
     * @return
     */
    @GetMapping("/findAdminById")
    public Result save(@RequestParam("id") String id) {
        Admin admin = adminService.getById(id);
        if(admin == null) {
            return Result.error("获取管理员失败！");
        }
        return Result.success("获取管理员从成功！", admin);
    }

    /**
     * 查询所有管理员
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<Admin> adminList = adminService.list();
        if(adminList != null) {
            return Result.success("查询所有管理员成功！", adminList);
        }
        return Result.error("查询所有管理员失败！");
    }

    /**
     *删除某个管理员
     * @param admin
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Admin admin) {
        boolean res = adminService.removeById(admin);
        if(res) {
            return Result.success("删除管理员成功！");
        }
        return Result.error("删除管理员失败！");
    }

    /**
     * 删除一系列管理员
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> adminIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = adminService.removeByIds(adminIds);
        if(res) {
            return Result.success("删除管理员成功！");
        }
        return Result.error("删除管理员失败！");
    }

    /**
     * 修改管理员
     * @param admin
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Admin admin) {
        String role1 = roleService.findNameByAuthority(admin.getRole());
        admin.setRoleName(role1);
        boolean res = adminService.saveOrUpdate(admin);
        if (res) {
            return Result.success("修改管理员成功！");
        }
        return Result.error("修改管理员失败！");
    }

    /**
     * 根据角色获取所有管理员
     * @param admin
     * @return
     */
    @PostMapping("/findAdminByRole")
    public Result findAdminByRole(@RequestBody Admin admin) {
        List<Admin> adminList;
        if(admin.getRole().equals("")) {
            adminList = adminService.list();
        }
        else {
            adminList = adminService.findAdminByRole(admin.getRole());
        }
        if(adminList != null) {
            for(Admin a : adminList) {
                String role1 = roleService.findNameByAuthority(a.getRole());
                a.setRoleName(role1);
            }
            return Result.success(adminList);
        }
        return Result.error("获取管理员信息失败");
    }

    /**
     * 分页查询所有的管理员
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String role,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        if(!role.isEmpty()&& !role.equals("全部")) {
            queryWrapper.eq("role", role);
        }
        queryWrapper.like("name", name);
        Page<Admin> adminPage = adminService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Admin> adminList = adminPage.getRecords();
        for(Admin admin : adminList) {
            String role1 = roleService.findNameByAuthority(admin.getRole());
            admin.setRoleName(role1);
        }
        return Result.success("成功查询所有管理员信息！",adminPage);
    }
    /**
     * 导出用户信息
     * @param name
     * @param response
     * @return
     */
    @GetMapping("exportAdminList")
    public Result exportAdminList(@RequestParam(defaultValue = "") String name,
                                  @RequestParam(defaultValue = "") String role,
                                         HttpServletResponse response) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        if(!role.isEmpty()) {
            queryWrapper.eq("role", role);
        }
        queryWrapper.like("name", name);
        List<Admin> adminList = adminService.list(queryWrapper);
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("用户名");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("角色");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("电话");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("邮箱");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        cell = row.createCell((short)7);
        cell.setCellValue("最近登录时间");
        cell.setCellStyle(style);
        cell = row.createCell((short)8);
        cell.setCellValue("登录IP");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < adminList.size(); i++) {
            row = sheet.createRow(i + 1);
            Admin admin = adminList.get(i);
            row.createCell((short) 0).setCellValue(admin.getId());
            row.createCell((short) 1).setCellValue(admin.getUsername());
            row.createCell((short) 2).setCellValue(admin.getName());
            row.createCell((short) 3).setCellValue(admin.getRole());
            row.createCell((short) 4).setCellValue(admin.getPhone());
            row.createCell((short) 5).setCellValue(admin.getEmail());
            row.createCell((short) 8).setCellValue(admin.getLoginIp());
            try {
                Date lastLoginTime=inputDateFormat.parse(admin.getLastLoginTime().toString());
                Date createTime = inputDateFormat.parse(admin.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 6).setCellValue(outputDateFormat.format(createTime));
                row.createCell((short)7).setCellValue((outputDateFormat.format(lastLoginTime)));
            } catch (ParseException e) {
                row.createCell((short) 6).setCellValue(admin.getCreateTime().toString());
                row.createCell((short) 7).setCellValue(admin.getLastLoginTime().toString());
            }
        }
        String fileName = "exportAdminList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportAdminList");
    }
}
